import { axios } from '@/utils/request'

const api = {
  dictData: '/system/dict/data',
  getHospitalInfo: '/hospitalInfo/getHospitalInfo',
  getHospitalInfoOut: '/hospitalInfo/getMyHospitalInfo',
  getHospDeptInfo: '/deptInfo/getHospDeptInfo',
  getDoctorInfoList: '/doctorInfo/getDoctorInfoList'
}

// 静态数据
export const staticDict = {
  patientMedicareType: [
    { label: '城镇职工基本医疗保险', value: '1' },
    { label: '城镇居民基本医疗保险', value: '2' },
    { label: '新型农村合作医疗', value: '3' },
    { label: '其他', value: '99' }
  ],
  patientType: [
    { label: '普通', value: '1' },
    { label: '急诊', value: '2' }
  ],
  hospitalTurn: [
    { label: '上转', value: '0' },
    { label: '下转', value: '1' }
  ],
  patientCertificateType: [
    { label: '居民身份证', value: '1' },
    { label: '驾驶证', value: '2' }
  ],
  patientGender: [
    { label: '男', value: '1' },
    { label: '女', value: '2' }
  ],
  // 暂时只显示待审核 0：暂存 1：待审核 2：审核通过 3：审核不通过 4:撤销
  approvalStatus: [
    {
      label: '暂存',
      value: '0'
    },
    {
      label: '待审核',
      value: '1'
    },
    {
      label: '审核通过',
      value: '2'
    },
    {
      label: '审核不通过',
      value: '3'
    }
  ]
}
function arrToMap (obj) {
  const newObj = {}
  Object.keys(obj).forEach((key) => {
    if (obj[key] instanceof Array && obj[key].length > 0) {
      const map = new Map()
      obj[key].forEach((d) => {
        map.set(d.value, d.label)
      })
      newObj[key] = map
    } else {
      newObj[key] = obj[key]
    }
  })
  // console.log('staticDictMap', newObj)
  return newObj
}

export const staticDictMap = arrToMap(staticDict)

// 特殊词典接口处理
export function getDict (api, params) {
  return new Promise((resolve, reject) => {
    // ajax
    axios({
      url: '/ref' + api,
      method: 'get',
      params: params
    }).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}
// 非动态数据开启缓存减少请求，优化性能，如需更新字典数据需重新启动,默认关闭
function getFormatDict ({ type, label, value, call, error, params = {}, cache = false }) {
  if (cache && sessionStorage.getItem(type)) {
    console.log(type, JSON.parse(sessionStorage.getItem(type)))
    call && call(JSON.parse(sessionStorage.getItem(type)))
  } else {
    getDict(api[type], params).then((res) => {
      if (res.code === 200) {
        const newArr = []
        const data = res.data
        if (data) {
          data.forEach((el, index) => {
            newArr.push({
              label: el[label],
              value: el[value]
            })
          })
          cache && sessionStorage.setItem(type, JSON.stringify(newArr))
          call && call(newArr)
        }
      } else {
        console.log('未获取到字典数据！')
      }
    }).catch(err => {
      error && error(err)
    })
  }
}
// 获取医院机构信息
export function getHospitalInfo () {
  return new Promise((resolve, reject) => {
    getFormatDict({
      type: 'getHospitalInfo',
      label: 'hospName',
      value: 'uid',
      call: resolve,
      error: reject,
      cache: false,
      params: {}
    })
  })
}

// 获取转出医院机构信息
export function getHospitalInfoOut () {
  return new Promise((resolve, reject) => {
    getFormatDict({
      type: 'getHospitalInfoOut',
      label: 'hospName',
      value: 'uid',
      call: resolve,
      error: reject,
      cache: false,
      params: {}
    })
  })
}

// 动态获取医院科室信息
export function getHospDeptInfo (val) {
  return new Promise((resolve, reject) => {
    getFormatDict({
      type: 'getHospDeptInfo',
      label: 'deptName',
      value: 'uid',
      call: resolve,
      error: reject,
      cache: false, // 动态数据禁用缓存
      params: { hopitalInfoId: val }
    })
  })
}
// 动态获取医生信息
export function getDoctorInfoList (params, call, err) {
  return new Promise((resolve, reject) => {
    getFormatDict({
      type: 'getDoctorInfoList',
      label: 'docName',
      value: 'uid',
      call: resolve,
      error: reject,
      cache: false, // 动态数据禁用缓存
      params: params
    })
  })
}
// 字典两种用法，各有优缺点
// 1.Map 需要数组的时候构造数组不方便
// operTypeMap = await getDictMap('sys_oper_type')
// this.operTypeMap = operTypeMap
// this.operTypeMap.forEach((value, key, mymap) => {
//   this.businessTypes.push({ code: key, label: value })
// })
// 2.数组 在modal调用没有map方便
// this.businessTypes = await getDictArray('sys_oper_type')
// this.businessTypes.map(d => {
//   operTypeMap[d.dictValue] = { text: d.dictLabel }
// })
// this.operTypeMap = operTypeMap

/**
 * 根据类型获取字典内容 返回Map
 * @param {String} dictType 字典类型
 */
function getDictAxios (dictType, resolve, reject) {
  let time = 0
  function request (dictType, resolve, reject) {
    axios({
      url: api.dictData + '/type',
      method: 'get',
      params: { 'dictType': dictType }
    }).then(response => {
      const res = response.data
      if (res && Object.keys(res).length > 0) {
        const map = new Map()
        Object.keys(res).forEach(key => {
          map.set(res[key].dictValue, res[key].dictLabel)
        })
        resolve(map)
      }
    }).catch(err => {
      // 服务出错或短暂网络故障处理,超过20次显示原始值
      if (time < 20) {
        setTimeout(() => {
          time++
          request(dictType, resolve, reject)
        }, 500)
      } else {
        console.error('词典获取服务错误', err)
        reject(err)
      }
    })
  }
  request(dictType, resolve, reject)
}
export function getDictMap (dictType) {
  return new Promise((resolve, reject) => {
    getDictAxios(dictType, resolve, reject)
  })
}
/**
 * 根据类型获取字典内容 返回数组
 * @param {String} dictType 字典类型
 */
export function getDictArray (dictType) {
  return axios({
    url: api.dictData + '/type',
    method: 'get',
    params: { 'dictType': dictType }
  })
}
